package org.carl.component.job.util

import jodd.http.Cookie
import jodd.http.HttpRequest
import jodd.http.HttpResponse
import jodd.net.HttpMethod
import java.nio.charset.Charset

/**
 * email carl.chen@bk.ru
 * @Author: 陈青松
 * @Date: 2019/2/21 18:11
 */
class HttpUtil {
    companion object {
        /**
         * 转换编码
         */
        fun to(data: String, charSet1: Charset, charSet2: Charset): String {
            return String(data?.toByteArray(charSet1), charSet2);
        }

        /**
         * 发送数据请求
         * @param hm
         * @param url
         * @param formMap
         * @param cookies
         * @param headerMap
         * @return
         */
        fun send(hm: HttpMethod, url: String, formMap: Map<String, Any?>?, headerMap: Map<String, String>?, vararg cookies: Cookie): HttpResponse? {
            var hr: HttpRequest? = null
            when (hm) {
                HttpMethod.GET -> {
                    hr = HttpRequest.get(url)
                    if (null != formMap) {
                        hr = hr.query(formMap as kotlin.collections.MutableMap<kotlin.String, kotlin.String>?)
                    }
                }
                HttpMethod.POST -> hr = HttpRequest.post(url)
                HttpMethod.PUT -> hr = HttpRequest.post(url)
                HttpMethod.DELETE -> hr = HttpRequest.delete(url)
                HttpMethod.OPTIONS -> hr = HttpRequest.options(url)
                HttpMethod.CONNECT -> hr = HttpRequest.connect(url)
                HttpMethod.HEAD -> hr = HttpRequest.head(url)
                HttpMethod.TRACE -> hr = HttpRequest.trace(url)
            }
            if (hr != null) {
                //添加form参数
                hr = if (formMap == null) hr else hr.form(formMap)
                /**
                 * 头信息
                 */
                hr = if (headerMap == null) hr else hr!!.header(headerMap)
                /**
                 * cookie
                 */
                hr!!.cookies(*cookies)
                hr?.charset("UTF-8")
                return hr!!.send()
            } else {
                return null
            }
        }

        /**
         * 获取urf-8
         */
        fun getUtf8(hr: HttpResponse): String {
            if (hr.statusCode() == 200) {
                return to(hr.body(), Charsets.ISO_8859_1, Charsets.UTF_8)
            }
            return hr.bodyText()
        }
    }
}